<template>
  <div class="chart-container">
    <!--
      图表联动实现说明：
      1. 每个图表都有唯一的ref引用，用于获取ECharts实例
      2. 所有图表都属于同一个group('linkedGroup')，实现基础联动
      3. 通过监听鼠标事件，实现自定义的精确联动控制
      4. 在数据加载完成后，通过ref获取图表实例并设置联动事件
    -->
    <!-- <h3 style="text-align: center;font-size: 26px;color: #FF0000;" v-if="errline">{{ errline }}</h3> -->
    <chart ref="chart1Ref" id="chart1" :group="'linkedGroup'" :options="chartOptions" height="350px" />
    <chart ref="chart2Ref" id="chart2" :group="'linkedGroup'" :options="currentChartOptions" height="350px"
      class="mt20" />
    <chart ref="chart3Ref" id="chart3" :group="'linkedGroup'" :options="currentChartOptions2" height="350px"
      class="mt20" />
    <chart ref="chart4Ref" id="chart4" :group="'linkedGroup'" :options="currentChartOptions3" height="350px"
      class="mt20" />
  </div>
</template>

<script setup>
/**
 * 故障波形图表展示组件
 * 包含两个图表：
 * 1. 主图表：显示A、B、C相电压和零线电压的波形
 * 2. 电流图表：单独显示故障点位传感器电流波形
 */

import { useDark } from '@vueuse/core'
const isDarkMode = useDark()
import chart from '@/components/chart';
import { ref, nextTick } from 'vue';
import * as echarts from 'echarts';
const route = useRoute();
const { proxy } = getCurrentInstance();

// 显示加载提示
proxy.$modal.loading("正在加载...");
const id = ref(null);
// 定义图表ref变量，用于获取ECharts实例
const chart1Ref = ref(null);
const chart2Ref = ref(null);
const chart3Ref = ref(null);
const chart4Ref = ref(null);

// 存储所有图表实例的数组，用于联动控制
const chartInstances = ref([]);

// 联动控制状态
const linkageState = ref({
  isLinking: false,        // 是否正在执行联动（防止循环触发）
  currentHoverIndex: -1,   // 当前鼠标悬停的数据点索引
  lastTriggerChart: null   // 最后触发联动的图表ID
});
const chartOptions = ref({
  group: 'linkedGroup',
  title: {
    text: '',
    left: 'center',
    textStyle: {
      color: '#ff0000',
      fontSize: 22,
    },
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: '#FF0000',
        width: 1,
      },
      // 联动配置：连接所有图表的X轴
      link: {
        xAxisIndex: 'all'  // 这会让所有图表的指示线同步移动
      }
    },
    // 自定义tooltip格式化函数
    formatter: function (params) {
      let result = '';
      params.forEach(param => {
        if (param.seriesName == '3U0电压') {
          result += param.seriesName + ': ' + param.value + 'V<br/>';
        } else {
          // 使用 toFixed(2) 确保结果最多两位小数
          result += param.seriesName + ': ' + Math.round(param.value * 100) + 'V<br/>';
        }
      });
      return result;
    }
  },
  legend: {
    type: 'scroll',
    top: '8%',
    left: 'center',
    textStyle: {
      color: '#333'
    },
    data: ['A相电压', 'B相电压', 'C相电压', '3U0电压'],
    selected: {
      'A相电压': true,
      'B相电压': true,
      'C相电压': true,
      '3U0电压': true
    }
  },
  color: ['#FFFF00', '#00FF00', '#FF0000', '#0000FF'],
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    show: true,
    data: [],
    axisLabel: {
      interval: function (index, total) {
        return total;
      }
    }
  },
  yAxis: {
    type: 'value',
    name: '电压(V)',
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '#666666'
      }
    },
    axisLabel: {
      formatter: '{value}'
    }
  },
  series: []
});

/**
* 电流图表配置
* 专门用于显示故障点位传感器电流数据
* X轴：显示三个关键点（-80、0、160）
* Y轴：显示电流值
*/
const currentChartOptions = ref({
  group: 'linkedGroup',
  title: {
    text: '',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 16
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: '#FF0000'
      },
      link: { xAxisIndex: 'all' }

    },
    formatter: function (params) {
      let result = '';
      params.forEach(param => {
        result += param.seriesName + ': ' + param.value + 'A<br/>';
      });
      return result;
    }
  },
  legend: {
    type: 'scroll',
    top: '5%',
    left: 'center',
    textStyle: {
      color: '#333'
    },
    selectedMode: false
  },
  color: ['#FF6600'],
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    show: true,
    data: [],
    axisLabel: {
      interval: function (index, total) {
        return total;
      }
    }
  },
  yAxis: {
    type: 'value',
    name: '电流(A)',
    min: -200,
    max: 200,
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    },
    axisLabel: {
      formatter: '{value}'
    }
  },
  series: []
});

const currentChartOptions2 = ref({
  group: 'linkedGroup',
  title: {
    text: '',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 16
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: '#FF0000'
      },
      link: { xAxisIndex: 'all' }

    },
    formatter: function (params) {
      let result = '';
      params.forEach(param => {
        result += param.seriesName + ': ' + param.value + 'A<br/>';
      });
      return result;
    }
  },
  legend: {
    type: 'scroll',
    top: '5%',
    left: 'center',
    textStyle: {
      color: '#333'
    },
    selectedMode: false
  },
  color: ['#FF6600'],
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    show: true,
    data: [],
    axisLabel: {
      interval: function (index, total) {
        return total;
      }
    }
  },
  yAxis: {
    type: 'value',
    name: '电流(A)',
    min: -200,
    max: 200,
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    },
    axisLabel: {
      formatter: '{value}'
    }
  },
  series: []
});

const currentChartOptions3 = ref({
  group: 'linkedGroup',
  title: {
    text: '',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 16
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: '#FF0000'
      },
      link: { xAxisIndex: 'all' }

    },
    formatter: function (params) {
      let result = '';
      params.forEach(param => {
        result += param.seriesName + ': ' + param.value + 'A<br/>';
      });
      return result;
    }
  },
  legend: {
    type: 'scroll',
    top: '5%',
    left: 'center',
    textStyle: {
      color: '#333'
    },
    selectedMode: false
  },
  color: ['#FF6600'],
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    show: true,
    data: [],
    axisLabel: {
      interval: function (index, total) {
        return total;
      }
    }
  },
  yAxis: {
    type: 'value',
    name: '电流(A)',
    min: -200,
    max: 200,
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    },
    axisLabel: {
      formatter: '{value}'
    }
  },
  series: []
});
// 监听主题变化
watch(isDarkMode, (newIsDarkMode) => {
  const textColor = newIsDarkMode ? '#fff' : '#333';
  // 更新主图表文字颜色
  // chartOptions.value.title.textStyle.color = textColor;
  chartOptions.value.legend.textStyle.color = textColor;
  // 更新电流图表文字颜色
  currentChartOptions.value.title.textStyle.color = textColor;
  currentChartOptions.value.legend.textStyle.color = textColor;
  currentChartOptions2.value.title.textStyle.color = textColor;
  currentChartOptions2.value.legend.textStyle.color = textColor;
  currentChartOptions3.value.title.textStyle.color = textColor;
  currentChartOptions3.value.legend.textStyle.color = textColor;
}, { immediate: true });
/**
 * 图表实例准备完成的回调函数
 * 当每个图表组件加载完成后，会调用对应的回调函数
 * 在这里我们获取ECharts实例并设置联动事件
 */

// 图表1准备完成回调
const onChart1Ready = (chartInstance) => {
  chartInstances.value[0] = chartInstance;
  setupChartLinkage(chartInstance, 'chart1');
};

// 图表2准备完成回调
const onChart2Ready = (chartInstance) => {
  chartInstances.value[1] = chartInstance;
  setupChartLinkage(chartInstance, 'chart2');
};

// 图表3准备完成回调
const onChart3Ready = (chartInstance) => {
  chartInstances.value[2] = chartInstance;
  setupChartLinkage(chartInstance, 'chart3');
};

// 图表4准备完成回调
const onChart4Ready = (chartInstance) => {
  chartInstances.value[3] = chartInstance;
  setupChartLinkage(chartInstance, 'chart4');
};

/**
 * 初始化所有图表的联动功能
 * 在数据加载完成后调用，确保所有图表都已经渲染完成
 */
const initializeChartLinkage = () => {
  // 使用nextTick确保DOM更新完成
  nextTick(() => {
    // 等待一小段时间确保图表完全渲染
    setTimeout(() => {

      // 通过DOM元素获取ECharts实例
      // 注意：chart组件内部的chartRef是DOM元素
      const chart1Dom = chart1Ref.value?.$refs?.chartRef;
      const chart2Dom = chart2Ref.value?.$refs?.chartRef;
      const chart3Dom = chart3Ref.value?.$refs?.chartRef;
      const chart4Dom = chart4Ref.value?.$refs?.chartRef;


      // 获取ECharts实例
      const chart1Instance = chart1Dom ? echarts.getInstanceByDom(chart1Dom) : null;
      const chart2Instance = chart2Dom ? echarts.getInstanceByDom(chart2Dom) : null;
      const chart3Instance = chart3Dom ? echarts.getInstanceByDom(chart3Dom) : null;
      const chart4Instance = chart4Dom ? echarts.getInstanceByDom(chart4Dom) : null;

      // 存储图表实例
      chartInstances.value = [chart1Instance, chart2Instance, chart3Instance, chart4Instance];

      // 为每个图表设置联动功能
      if (chart1Instance) {
        setupChartLinkage(chart1Instance, 'chart1');
      }
      if (chart2Instance) {
        setupChartLinkage(chart2Instance, 'chart2');
      }
      if (chart3Instance) {
        setupChartLinkage(chart3Instance, 'chart3');
      }
      if (chart4Instance) {
        setupChartLinkage(chart4Instance, 'chart4');
      }

      // 暴露调试函数到全局，方便在控制台测试
      window.chartDebug = {
        instances: chartInstances.value,
        testLinkage: (dataIndex = 100) => {
          triggerOtherChartsTooltip(dataIndex, 'chart1');
        },
        hideLinkage: () => {
          hideOtherChartsTooltip('none');
        },
        showChartInfo: () => {
        }
      };

    }, 1000); // 等待1000ms确保图表完全渲染
  });
};

/**
 * 设置图表联动功能
 * @param {Object} chartInstance - ECharts实例
 * @param {String} chartId - 图表唯一标识
 */
const setupChartLinkage = (chartInstance, chartId) => {
  if (!chartInstance) {
    console.warn(`${chartId} 图表实例为空，无法设置联动`);
    return;
  }


  // 监听鼠标移入数据点事件 - 当鼠标悬停在数据点上时触发
  chartInstance.on('mouseover', 'series', (params) => {
    // 防止循环触发联动
    if (linkageState.value.isLinking) return;


    // 设置联动状态
    linkageState.value.isLinking = true;
    linkageState.value.currentHoverIndex = params.dataIndex;
    linkageState.value.lastTriggerChart = chartId;

    // 触发其他图表的联动显示
    triggerOtherChartsTooltip(params.dataIndex, chartId);

    // 重置联动状态
    setTimeout(() => {
      linkageState.value.isLinking = false;
    }, 100);
  });

  // 监听鼠标移出数据点事件 - 当鼠标离开数据点时触发
  chartInstance.on('mouseout', 'series', () => {
    // 防止循环触发
    if (linkageState.value.isLinking) return;


    // 设置联动状态
    linkageState.value.isLinking = true;
    linkageState.value.currentHoverIndex = -1;
    linkageState.value.lastTriggerChart = chartId;

    // 隐藏其他图表的tooltip
    hideOtherChartsTooltip(chartId);

    // 重置联动状态
    setTimeout(() => {
      linkageState.value.isLinking = false;
    }, 100);
  });

  // 监听图表区域鼠标移动事件 - 实现更精确的联动控制
  chartInstance.getZr().on('mousemove', (event) => {
    // 防止循环触发联动
    if (linkageState.value.isLinking) return;

    // 获取鼠标位置对应的数据点
    const pointInPixel = [event.offsetX, event.offsetY];
    const pointInGrid = chartInstance.convertFromPixel('grid', pointInPixel);

    if (pointInGrid && pointInGrid[0] !== null) {
      const xIndex = Math.round(pointInGrid[0]);

      // 只有当数据点索引发生变化时才触发联动
      if (linkageState.value.currentHoverIndex !== xIndex && xIndex >= 0) {

        linkageState.value.isLinking = true;
        linkageState.value.currentHoverIndex = xIndex;
        linkageState.value.lastTriggerChart = chartId;

        // 触发其他图表的联动显示
        triggerOtherChartsTooltip(xIndex, chartId);

        setTimeout(() => {
          linkageState.value.isLinking = false;
        }, 50);
      }
    }
  });

};

/**
 * 触发其他图表显示tooltip
 * @param {Number} dataIndex - 数据点索引
 * @param {String} excludeChartId - 排除的图表ID（触发联动的图表）
 */
const triggerOtherChartsTooltip = (dataIndex, excludeChartId) => {

  chartInstances.value.forEach((instance, index) => {
    if (!instance) {
      console.warn(`图表实例 ${index} 为空`);
      return;
    }

    // 获取当前图表的ID
    const currentChartId = ['chart1', 'chart2', 'chart3', 'chart4'][index];

    // 跳过触发联动的图表本身
    if (currentChartId === excludeChartId) {
      return;
    }
    try {
      // 使用ECharts的dispatchAction方法触发tooltip显示
      instance.dispatchAction({
        type: 'showTip',        // 显示tooltip的动作类型
        seriesIndex: 0,         // 系列索引，0表示第一个系列
        dataIndex: dataIndex    // 数据点索引
      });
    } catch (error) {
    }
  });
};

/**
 * 隐藏其他图表的tooltip
 * @param {String} excludeChartId - 排除的图表ID（触发联动的图表）
 */
const hideOtherChartsTooltip = (excludeChartId) => {
  chartInstances.value.forEach((instance, index) => {
    if (!instance) {
      return;
    }

    // 获取当前图表的ID
    const currentChartId = ['chart1', 'chart2', 'chart3', 'chart4'][index];

    // 跳过触发联动的图表本身
    if (currentChartId === excludeChartId) {
      return;
    }
    try {
      // 使用ECharts的dispatchAction方法隐藏tooltip
      instance.dispatchAction({
        type: 'hideTip'         // 隐藏tooltip的动作类型
      });
    } catch (error) {
    }
  });
};

// 组件挂载时初始化图表数据
onMounted(() => {
  // 添加 passive 事件监听器配置
  const chartContainer = document.querySelector('.chart-container');
  if (chartContainer) {
    chartContainer.addEventListener('mousewheel', () => { }, { passive: true });
  }
  id.value = route.query.id;
  const { dev_Name, dev_id, alarmtime } = route.query;
  proxy.cloudTv_API.FindOneAlarmGnd({ id: id.value }).then(res => {
    const data = {
      series: [
        { name: 'A相电压', data: res.data.ua_wave.split(',') },
        { name: 'B相电压', data: res.data.ub_wave.split(',') },
        { name: 'C相电压', data: res.data.uc_wave.split(',') },
        { name: '3U0电压', data: res.data.u0_wave.split(',') },
      ]
    };
    // console.log(res.data.ua_wave.split(',').length);
    // console.log(res.data.ub_wave.split(',').length);
    // console.log(res.data.uc_wave.split(',').length);
    // console.log(res.data.u0_wave.split(',').length);
    // console.log(res.data.current_wave[0].senseWave.split(',').length);

    // 获取 A 相电压数据长度作为基准，假设各相数据长度一致
    const dataLength = res.data.ua_wave.split(',').length;
    const xAxisData = new Array(dataLength).fill('');
    // 计算每组的间隔点数
    const intervalPoints = Math.floor((dataLength - 1) / 12);
    // 动态为 xAxisData 赋值
    for (let i = 0; i < 12; i++) {
      const index = i * intervalPoints;
      xAxisData[index] = `${-80 + i * 20}(ms)`;
    }
    // 确保最后一个点显示 160(ms)
    if (dataLength > 0) {
      xAxisData[dataLength - 1] = '160(ms)';
    }
    xAxisData[dataLength - 1] = '160(ms)';
    chartOptions.value.title.text = `${res?.data?.error_line} — ${dev_Name}(${dev_id}) — ${alarmtime}`;
    chartOptions.value.xAxis.data = xAxisData;
    /**
     * X轴刻度处理
     * 总共768个数据点，但只在三个关键位置显示刻度值：
     * 1. 第1个点(index=0)：显示-80
     * 2. 第256个点(index=255)：显示0
     * 3. 第768个点(index=767)：显示160
     * 其他位置显示空字符串，保持图表整洁
     */
    // 更新主图表
    chartOptions.value.series = data.series.map(item => ({
      name: item.name,
      type: 'line',
      smooth: false,
      symbol: 'circle',
      symbolSize: 0,
      data: item.data,
      itemStyle: {
        normal: {
          lineStyle: {
            width: 1
          }
        }
      }
    }));
    const current_wave1 = res.data.current_wave[0];
    const current_wave2 = res.data.current_wave[1];
    const current_wave3 = res.data.current_wave[2];
    // 更新电流图表
    currentChartOptions.value.xAxis.data = xAxisData;
    currentChartOptions.value.series = [{
      name: `故障点位传感器 - CAN：${current_wave1.senserName} - 柜体：${current_wave1.cabinet} - Rms：${current_wave1.senser_Rms}`,
      type: 'line',
      smooth: false,
      symbol: 'circle',
      symbolSize: 0,
      data: current_wave1.senseWave.split(','),
      itemStyle: { normal: { lineStyle: { width: 1 } } }
    }];
    // 更新电流图表
    currentChartOptions2.value.xAxis.data = xAxisData;
    currentChartOptions2.value.series = [{
      name: `故障点位传感器 - CAN：${current_wave2.senserName} - 柜体：${current_wave2.cabinet} - Rms：${current_wave2.senser_Rms}`,
      type: 'line',
      smooth: false,
      symbol: 'circle',
      symbolSize: 0,
      data: current_wave2.senseWave.split(','),
      itemStyle: { normal: { lineStyle: { width: 1 } } }
    }];
    // 更新电流图表
    currentChartOptions3.value.xAxis.data = xAxisData;
    currentChartOptions3.value.series = [{
      name: `故障点位传感器 - CAN：${current_wave3.senserName} - 柜体：${current_wave3.cabinet} - Rms：${current_wave3.senser_Rms}`,
      type: 'line',
      smooth: false,
      symbol: 'circle',
      symbolSize: 0,
      data: current_wave3.senseWave.split(','),
      itemStyle: { normal: { lineStyle: { width: 1 } } }
    }];

    // 数据加载完成后，初始化图表联动功能
    initializeChartLinkage();


  }).finally(() => {
    proxy.$modal.closeLoading();
  });
});
</script>

<style lang="scss" scoped>
.chart-container {
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 84px);
  overflow-y: auto;

  .mt20 {
    margin-top: 20px;
  }

  // 普通主题文字颜色
  color: #333;

  &.dark-mode {
    // 暗黑主题文字颜色
    color: white;
  }
}

// 图表标题、图例等文字颜色
.chart-container .chart-title,
.chart-container .legend-text {
  color: inherit;
}
</style>